const cds = require("@sap/cds");
const { exec } = require("child_process");

module.exports = (srv) => {
  const { RootCertificateAuthoritys } = srv.entities("ct.cert01");

  srv.on("testActionItem", async (req) => {
    const oCert = await cds.run(
      SELECT.one.from(RootCertificateAuthoritys).where({ ID: req.params[0].ID })
    );
    let sAlias = oCert.alias.replace(/\s/g, "-");
    let sOpensslCmd = `openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=${oCert.countryName}/ST=${oCert.stateName}/L=${oCert.localityName}/O=${oCert.organizationName}/OU=${oCert.organizationUnitName}/CN=${oCert.commonName}/emailAddress=${oCert.emailAddress}" -keyout ${sAlias}.key -out ${sAlias}.cert`;
    // let sOpensslCmd_certOnly = `openssl req -x509 -sha256 -new -nodes -key rootCAKey.pem -out ${sAlias}Cert.pem -subj "/C=${oCert.countryName}/ST=${oCert.stateName}/L=${oCert.localityName}/O=${oCert.organizationName}/OU=${oCert.organizationUnitName}/CN=${oCert.commonName}/emailAddress=${oCert.emailAddress}"`
    console.log(sOpensslCmd);
    exec(sOpensslCmd, (error, stdout, stderr) => {
      if (error) {
        console.log(`error: ${error.message}`);
        return;
      }
      if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
    });
    return req.reply({ result: "success" });
  });
};
